import * as express from 'express';
import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { LoggerService as MyLogger } from './common/modules/Logger/logger.service';

import { EnvHostOptions } from './common/config/env/host.config';
import { EnvSwaggerOptions } from './common/config/env/swagger.config';
import { terminalHelpTextConsole } from './utils/terminal-help-text-console';

const logger = new MyLogger();

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: logger,
  });

  app.use(express.json()); // For parsing application/json
  app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded

  const configService = app.get(ConfigService);
  // swagger option setting
  const swaggerOpts = configService.get<EnvSwaggerOptions>('EnvSwaggerOptions');
  const hostOpts = configService.get<EnvHostOptions>('EnvHostOptions');

  app.setGlobalPrefix(swaggerOpts.prefix);
  const config = new DocumentBuilder()
    .setTitle(swaggerOpts.title)
    .setDescription(swaggerOpts.desc)
    .setVersion(swaggerOpts.version)
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup(swaggerOpts.setupUrl, app, document, {
    customSiteTitle: swaggerOpts.title,
    swaggerOptions: {
      docExpansion: 'list',
      filter: true,
      showRequestDuration: true,
    },
  });

  await app.listen(hostOpts.port);

  logger.log(`设置应用程序端口号：${hostOpts.port}`, 'bootstrap');
  logger.log(
    `应用程序接口地址： http://localhost:${hostOpts.port}/${swaggerOpts.prefix}`,
    'bootstrap',
  );
  logger.log(
    `应用程序文档地址： http://localhost:${hostOpts.port}/${swaggerOpts.setupUrl}`,
    'bootstrap',
  );
  logger.log('🚀 服务应用已经成功启动！', 'bootstrap');
}
bootstrap().then(() => {
  terminalHelpTextConsole();
});
